import 'package:dio/dio.dart';
import 'package:flutter_house_manager/constants/index.dart';

class Requestdio {
  final _dio = Dio();
  //1、定义构造函数
  Requestdio() {
    //正常写法
    //基础地址
    _dio.options.baseUrl = GlobalVariable.BASE_URL;
    //连接超时时间
    _dio.options.connectTimeout =
        const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT);
    //接收超时时间
    _dio.options.receiveTimeout =
        const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT);

    //链式写法
    // _dio.options..baseUrl=GlobalVariable.BASE_URL
    // ..connectTimeout=const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT)
    // ..receiveTimeout=const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT);
    //添加拦截器
    _dio.interceptors.add(InterceptorsWrapper(onRequest: (context, handler) {
      // 请求拦截器
      // 注入token

      handler.next(context);
    }, onResponse: (context, handler) {
      // 响应拦截器
      if (context.statusCode! >= 200 && context.statusCode! <= 300) {
        //响应成功
        handler.next(context);
      } else {
        //响应失败
        handler.reject(DioException(requestOptions: context.requestOptions));
      }
    },
        // 错误拦截器
        onError: (context, handler) {
      handler.reject(context);
    }));
  }
  //2、定义请求方法
  get(String url, {Map<String, dynamic>? params}) {
    return _handleRes(_dio.get(url, queryParameters: params));
  }

  //post方法
  post(String url, {Map<String, dynamic>? data}) {
    return _handleRes(_dio.post(url, data: data));
  }

  //put方法
  put(String url, {Map<String, dynamic>? data}) {
    return _handleRes(_dio.put(url, data: data));
  }

  //delete方法
  delete(String url,
      {Map<String, dynamic>? params, Map<String, dynamic>? data}) {
    return _handleRes(_dio.delete(url, queryParameters: params, data: data));
  }

  //3、数据剥离
  _handleRes(Future<Response<dynamic>> task) async {
    final res = await task;
    //请求成功
    if (res.data["code"] == GlobalVariable.SUCCESS_CODE) {
      return res.data['data'];
    } else {
      throw DioException(requestOptions: res.requestOptions);
    }
  }
}

//单例导出
final Requestdio requestdio = Requestdio();
